package com.sctvcloud.qingchuan.ui.activities;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.luck.picture.lib.PictureExternalPreviewActivity;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomCheckBox;
import com.ruihang.generalibrary.ui.widget.CustomFontEditText;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.sctvcloud.qingchuan.R;
import com.sctvcloud.qingchuan.application.Cache;
import com.sctvcloud.qingchuan.application.Constances;
import com.sctvcloud.qingchuan.base.BaseActivity;
import com.sctvcloud.qingchuan.beans.FUsers;
import com.sctvcloud.qingchuan.beans.PoliticsImgUpbean;
import com.sctvcloud.qingchuan.beans.PoliticsUpVideo;
import com.sctvcloud.qingchuan.http.AbsNetCallBack;
import com.sctvcloud.qingchuan.http.NetUtils;
import com.sctvcloud.qingchuan.ui.adapter.RebllionCommitAdapter;
import com.sctvcloud.qingchuan.ui.dialog.ConfirmDialogFragment;
import com.sctvcloud.qingchuan.ui.dialog.PicChoiceDiaFragment;
import com.sctvcloud.qingchuan.ui.dialog.ProtocolFragment;
import com.sctvcloud.qingchuan.ui.dialog.RebllionDiaFragment;
import com.sctvcloud.qingchuan.ui.dialog.ShotChoiceDiaFragment;
import com.sctvcloud.qingchuan.ui.fragment.RebllionFragment;
import com.sctvcloud.qingchuan.ui.utils.DataUtils;
import com.sctvcloud.qingchuan.ui.utils.PermissionUtils;
import com.sctvcloud.qingchuan.ui.utils.PictureUtils;
import com.sctvcloud.qingchuan.ui.utils.TitleUtils;
import com.sctvcloud.qingchuan.ui.utils.UiListMarginUtils;
import com.sctvcloud.qingchuan.utils.GaoDeLocationUtil;
import com.sctvcloud.qingchuan.utils.ListTypeUtils;
import com.sctvcloud.qingchuan.utils.UserManager;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static com.sctvcloud.qingchuan.application.Constances.REBLLION_KEY;

/**
 * 问政模块  提交新的问政
 */
public class PoliticsCommitActivity extends BaseActivity implements RebllionCommitAdapter.RemainListSize, TextWatcher, CompoundButton.OnCheckedChangeListener, GaoDeLocationUtil.LocationChangeListener {
    @BindView(R.id.title_top_edit_topic)
    protected CustomFontTextView publish;
    @BindView(R.id.politics_commit_content)
    protected CustomFontEditText politics_content;
    @BindView(R.id.politics_commit_obj)
    protected CustomFontTextView politicsObj;
    @BindView(R.id.politics_commit_address_title)
    protected CustomFontTextView address_cv;
    @BindView(R.id.politics_commit_pic_list)
    protected RecyclerView pic_list;
    @BindView(R.id.politics_commit_prompt)
    protected CustomFontTextView prompt;

    //    @BindView(R.id.id_flowlayout)
//    protected TagFlowLayout flowLayout;
    @BindView(R.id.ck_annoy)
    protected CustomCheckBox push_cb;

    @BindView(R.id.politics_commit_title)
    protected CustomFontEditText politics_commit_title;
    @BindView(R.id.politics_commit_name)
    protected CustomFontEditText politics_commit_name;
    @BindView(R.id.politics_commit_contact)
    protected CustomFontEditText politics_commit_contact;
    @BindView(R.id.tv_rules)
    protected TextView tv_rules;

    private RebllionDiaFragment rebllionDiaFragment;
    private PicChoiceDiaFragment picChoiceDiaFragment;
    private ShotChoiceDiaFragment shotChoiceDiaFragment;
    private RebllionCommitAdapter adapter;
    private GridLayoutManager manger;
    private List<LocalMedia> selectList = new ArrayList<>();

    private Handler mHandler;
    private int maxSelectNum = 9;
    private int type = TYPE_CAMERA_PIC;  //type为0 拍照 1 录像 2图片
    private int rebellionType = Constances.REBELLION_TYPE_BREAKING_NEWS;
    private List<LocalMedia> currentList = new ArrayList<>();
    private int themeId;
    private boolean isLongClick = true;
    private String mVideoCoverImage;
    private int mLocationState = 0; //0正在定位，1定位成功，2定位失败
    private long mLocationTime = 0;
    private PermissionUtils mPermissionUtils;
    public static final int REQUEST_CODE = 8;
    public static final int CHOOSE_POLITICS_OBJ = 10;
    public static final String REBLLION_TAG = "dia_rebllion_fragment";
    public static final String PIC_TAG = "dia_pic_choice_fragment";
    public static final String SHOT_TAG = "dia_shot_choice_fragment";
    public static final String PROTOCOL_TAG = "protocol";

    public static final String VALS = "vals";

    public static final int TYPE_CAMERA_PIC = 0;
    public static final int TYPE_VIDEO = 1;
    public static final int TYPE_PIC = 2;
    private long politicsObjId;//问政对象ID

    private int locateFailTimes = 0;
    private ProtocolFragment protocolFragment;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this).useAndSetTxTitle("添加内容");
        themeId = R.style.picture_default_style;
        mHandler = new Handler();
        initView();
    }


    @Override
    protected void initInject() {
        setContentView(R.layout.activity_politics_commit);
        ButterKnife.bind(this);
    }


    private void initView() {
        publish.setVisibility(View.VISIBLE);
//        publish.setFocusable(true);
//        publish.setFocusableInTouchMode(true);
//        publish.requestFocus();
        tv_rules.setText(Html.fromHtml("<font color=\"#989898\">" + getResources().getString(R.string.text_rules) + "</font>" +
                "<font color=\"#358BFF\">" + getResources().getString(R.string.text_rules_item_5) + "</font>" + "<br>" + "<font color=\"#989898\">" + getResources().getString(R.string.show_after_audit) + "</font>" + "<br>"));

        manger = new GridLayoutManager(this, 3);
        pic_list.setItemAnimator(new DefaultItemAnimator());
        manger.setSmoothScrollbarEnabled(true);
        manger.setAutoMeasureEnabled(true);
        pic_list.setHasFixedSize(true);
        pic_list.setNestedScrollingEnabled(false);
        pic_list.setLayoutManager(manger);
        new UiListMarginUtils().setMargin(this, pic_list, R.dimen.item_list_large_margin_left, R.dimen.item_list_large_margin_right);
        int type = getIntent().getIntExtra(RebllionFragment.EX_TYPE, -1);
        if (type > 0) {
            selectList = (ArrayList<LocalMedia>) getIntent().getSerializableExtra(EX_DATA);
            if (selectList != null) {
                currentList.addAll(selectList);
                prompt.setVisibility(View.GONE);
            }

        }
        adapter = new RebllionCommitAdapter(this, selectList).setItemInternalClick(picItemClick).setRemainListSize(this);
        adapter.setOnLongItemClick(onLongClick);
        pic_list.setAdapter(adapter);
        politics_content.addTextChangedListener(this);
        rebellionType = (int) SharedPreferencesUtil.getParam(this, REBLLION_KEY, 1);
        refreshLocationState(null);
        checkLocationPermission();

//        mInflater = LayoutInflater.from(this);

//        tagAdapter = new TagAdapter<TopicContent>(mVals) {
//
//            @Override
//            public View getView(FlowLayout parent, int position, TopicContent s) {
//                TextView tv = (TextView) mInflater.inflate(R.layout.flow_text,
//                        flowLayout, false);
//                tv.setText(s.getTopicContent());
//                return tv;
//            }
//
//            @Override
//            public boolean setSelected(int position, TopicContent s) {
//                return false;
//            }
//        };
//
//        flowLayout.setAdapter(tagAdapter);
//        flowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
//            @Override
//            public boolean onTagClick(View view, int position, FlowLayout parent) {
//                return true;
//            }
//        });
//
//        flowLayout.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
//            @Override
//            public void onSelected(Set<Integer> selectPosSet) {
//                if (null != selectPosSet && selectPosSet.size() > 0) {
//                    for (Integer i : selectPosSet) {
//                        tp = tagAdapter.getItem(i);
//                    }
//                } else {
//                    tp = null;
//                }
//
//            }
//
//        });
    }


    @Override
    public void onResume() {
        super.onResume();

    }

    @OnClick(value = {R.id.title_top_edit_topic, R.id.politics_commit_address_title, R.id.tv_rules, R.id.politics_obj})
    public void rebllionClick(View view) {
        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
        pairs.add(new Pair<>("页面", "投稿"));
        switch (view.getId()) {
            case R.id.title_top_edit_topic:

                pairs.add(new Pair<>("行为类型", "输入"));
                GridsumWebDissector.getInstance().trackEvent(this, "", "发布", "", 200, pairs);
                uploadData();

                break;
            case R.id.politics_commit_address_title:
                if (mLocationState == 0) {
                    pairs.add(new Pair<>("行为类型", "输入"));
                    GridsumWebDissector.getInstance().trackEvent(this, "", "地点", "", 200, pairs);
                    checkLocationPermission();
                } else if (mLocationState == 2) {
                    checkLocationPermission();
                }
                break;
            case R.id.tv_rules:
                showProtocol();
                break;
            case R.id.politics_obj:
                Intent intent = new Intent(this, PoliticsChooseObjActivity.class);
                intent.putExtra(PoliticsChooseObjActivity.POLITICS_OBJ_ID, politicsObjId);
                startActivityForResult(intent, CHOOSE_POLITICS_OBJ);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    Log.e("path", "==pic==" + selectList.toString() + selectList.size() + type);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的

                    if (type == TYPE_CAMERA_PIC) {
                        currentList.addAll(selectList);
                        selectList = currentList;
                        if (adapter.getEqualDatas() == selectList) {
                            adapter.notifyDataSetChanged();
                        } else {
                            adapter.setData(selectList);
                        }
                    } else if (type == TYPE_VIDEO) {
                        adapter.setData(selectList);
                        currentList.clear();
                        currentList.addAll(selectList);

                    } else if (type == TYPE_PIC) {
                        adapter.setData(selectList);
                        currentList.clear();
                        currentList.addAll(selectList);

                    }
                    break;
                case REQUEST_CODE:
                    int pos = data.getIntExtra(PictureExternalPreviewActivity.POS, 0);
                    if (pos > 0) {
                        selectList = (List<LocalMedia>) data.getSerializableExtra(PictureExternalPreviewActivity.PIC_LIST);
                        adapter.setData(selectList);
                    } else {
                        adapter.clean();
                        selectList.clear();
                    }
                    break;
                case CHOOSE_POLITICS_OBJ:
                    politicsObjId = data.getLongExtra(PoliticsChooseObjActivity.POLITICS_OBJ_ID, 0);
                    String politicsObjName = data.getStringExtra(PoliticsChooseObjActivity.POLITICS_OBJ_NAME);
                    politicsObj.setText(politicsObjName);
                    break;

            }
        }
    }

    private void getShotDiaFragment() {
        if (shotChoiceDiaFragment == null) {
            shotChoiceDiaFragment = new ShotChoiceDiaFragment();
        }
        shotChoiceDiaFragment.setCallBack(shotCallBack);
        shotChoiceDiaFragment.show(getSupportFragmentManager(), SHOT_TAG);
    }

    BaseDialogFragment.ICallBack picCallBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == 1) {
                if (selectList.size() != 0) {
                    int pictureType = PictureMimeType.isPictureType(selectList.get(0).getPictureType());
                    if (pictureType == 2 && selectList.size() == 1) {
                        toast("只能选择一个视频");
                    } else {
                        getShotDiaFragment();
                    }
                } else {
                    getShotDiaFragment();
                }
            } else if (msg.what == 2) {
                type = TYPE_PIC;
                PictureUtils.choicePic(PoliticsCommitActivity.this, themeId, selectList);
            }
        }
    };
    BaseDialogFragment.ICallBack shotCallBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == 1) {
                type = TYPE_CAMERA_PIC;
                PictureUtils.choicePhoto(PoliticsCommitActivity.this);
            } else if (msg.what == 2) {
                type = TYPE_VIDEO;
                if (selectList != null) {
                    selectList.clear();
                }
                PictureUtils.choiceVideo(PoliticsCommitActivity.this);
            }
        }
    };
    OnItemInternalClick picItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            if (selectList == null) {
                return;
            }
            if (position == adapter.getItemCount() - 1) {
                if (selectList.size() < 9) {
                    if (picChoiceDiaFragment == null) {
                        picChoiceDiaFragment = new PicChoiceDiaFragment();
                    }
                    picChoiceDiaFragment.setCallBack(picCallBack);
                    if (!picChoiceDiaFragment.isShowing()) {
                        picChoiceDiaFragment.show(getSupportFragmentManager(), PIC_TAG);
                    }
                    prompt.setVisibility(View.GONE);
                } else {
                    toast(getString(R.string.rebllion_publish_pic_total));
                }

            } else {
                LocalMedia media = adapter.getItem(position);
                String pictureType = media.getPictureType();
                int mediaType = PictureMimeType.pictureToVideo(pictureType);
                switch (mediaType) {
                    case 1:
                        // 预览图片 可自定长按保存路径
                        Intent intent = new Intent(PoliticsCommitActivity.this, PictureExternalPreviewActivity.class);
                        intent.putExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST, (Serializable) selectList);
                        intent.putExtra(PictureConfig.EXTRA_POSITION, position);
                        intent.putExtra(PictureConfig.DIRECTORY_PATH, "/custom_file");
                        startActivityForResult(intent, REQUEST_CODE);
                        overridePendingTransition(com.luck.picture.lib.R.anim.a5, 0);
                        break;
                    case 2:
                        // 预览视频
                        PictureSelector.create(PoliticsCommitActivity.this).externalPictureVideo(media.getPath());
                        break;
                    case 3:
                        // 预览音频
                        PictureSelector.create(PoliticsCommitActivity.this).externalPictureAudio(media.getPath());
                        break;
                }
            }
        }
    };

    OnItemInternalClick onLongClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            if (isLongClick) {
                adapter.setEdting(true);
                isLongClick = false;
            } else {
                adapter.setEdting(false);
                isLongClick = true;
            }
        }
    };

    @Override
    public void getRemainListSize(List<LocalMedia> list) {
        selectList = list;
        currentList = list;
        adapter.notifyDataSetChanged();
    }

    /**
     * 发表报料内容
     */
    public void uploadData() {
        Cache.getInstance().setUploadReb(true);
        if (currentList.size() > 0) {
            List<String> picList = new ArrayList<>();
            if (PictureMimeType.pictureToVideo(currentList.get(0).getPictureType()) == 1) {
                if(inputCheck()) {
                    showProgress("正在上传图片...", false);
                    //如果爆料的是图片内容，直接上传
                    for (int i = 0; i < currentList.size(); i++) {
                        if (TextUtils.isEmpty(currentList.get(i).getCompressPath())) {
                            picList.add(currentList.get(i).getPath());
                        } else {
                            picList.add(currentList.get(i).getCompressPath());
                        }
                    }
                    MultipartBody.Builder mbody = new MultipartBody.Builder().setType(MultipartBody.FORM);
                    for (int i = 0; i < picList.size(); i++) {
                        File file = new File(picList.get(i));
                        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);//表单类型
                        mbody.addFormDataPart("file", file.getName(), body); //添加图片数据，body创建的请求体
                    }
//4.创建List<MultipartBody.Part> 集合，
//  调用MultipartBody.Builder的build()方法会返回一个新创建的MultipartBody
//  再调用MultipartBody的parts()方法返回MultipartBody.Part集合
                    List<MultipartBody.Part> parts = mbody.build().parts();
                    NetUtils.getNetAdapter().toCommitPoliticsImg(getOwnerName(), Constances.TENANT_ID, parts, mImgCallback);
                }
            } else if ((PictureMimeType.pictureToVideo(currentList.get(0).getPictureType()) == 2)) {
                //如果爆料的是视频内容，先压缩再上传
                if (inputCheck() &&null != currentList && currentList.size() > 0 && !TextUtils.isEmpty(currentList.get(0).getPath())) {
                    if (null != currentList.get(0)) {
                        showProgress("正在上传视频...", false);
                        MultipartBody.Builder mbody = new MultipartBody.Builder().setType(MultipartBody.FORM);
                        String fi = currentList.get(0).getPath();
                        File file = new File(fi);
                        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);//表单类型
                        mbody.addFormDataPart("file", file.getName(), body); //添加图片数据，body创建的请求体
//4.创建List<MultipartBody.Part> 集合，
//  调用MultipartBody.Builder的build()方法会返回一个新创建的MultipartBody
//  再调用MultipartBody的parts()方法返回MultipartBody.Part集合
                        List<MultipartBody.Part> parts = mbody.build().parts();
                        NetUtils.getNetAdapter().toCommitPoliticsVideo(getOwnerName(), Constances.TENANT_ID, parts, mVideoCallback);
                    }
                }
            }
        } else {
            if(inputCheck()) {
                publish(null, null);
            }
        }
    }


    /**
     * 提交 报料内容
     */
    private void publish(PoliticsImgUpbean imgs, List<PoliticsUpVideo> video) {
        showProgress("正在提交...");
        Map<String, Object> pe = new HashMap<>();
        FUsers fUsers = UserManager.getInstance().getUser();
        if (!TextUtils.isEmpty(fUsers.getUserId())) {
            pe.put("userId", Long.parseLong(fUsers.getUserId()));
            pe.put("nickName", fUsers.getNickName());
        }
        pe.put("content", politics_content.getText().toString());
        if (mLocationState == 0 || mLocationState == 2) {
            address_cv.setText("");
        }
//        if (politicsObjId > 0) {
//            pe.put("targetDepartment", politicsObjId);
//        }
        pe.put("title", TextUtils.isEmpty(politics_commit_title.getText().toString()) ? "" : politics_commit_title.getText().toString());
        pe.put("allowConnection", push_cb.isChecked() ? 1 : 0);
        pe.put("realyName", politics_commit_name.getText().toString().trim());
        pe.put("mobile", politics_commit_contact.getText().toString().trim());

        if (null != imgs && ListUtils.isListValued(imgs.getReturnIDs())) {
            String imgIds = "";
            if (imgs.getReturnIDs().size() > 1) {
                for (int i = 0; i < imgs.getReturnIDs().size() - 1; i++) {
                    imgIds += imgs.getReturnIDs() + ",";
                }
                imgIds += imgs.getReturnIDs().get(imgs.getReturnIDs().size() - 1);
            } else {
                imgIds += imgs.getReturnIDs().get(0);
            }
            pe.put("images", imgIds);
        }
        if (ListUtils.isListValued(video)) {
            pe.put("interactionInfoVideoUrl", video.get(0).getUrl());
        }
        pe.put("address", address_cv.getText().toString());
//        pe.put("siteNumber", Constances.SITE_ID);

        RequestBody body = DataUtils.toRequestBody(pe);
        NetUtils.getNetAdapter().toCommitPolitics(getOwnerName(), Constances.TENANT_ID, body, new AbsNetCallBack<String>(String.class) {
            @Override
            public void onSucStr(String singleResult) {
                if (singleResult == null) {
                    return;
                }
                toast("添加成功");
                if (UserManager.isLoginS()) {
                    StatisticsMainInit.reportLog(UserManager.getInstance().getUser().getPhoneNumber(),"",
                            politics_commit_title.getText().toString());
                }else{
                    StatisticsMainInit.reportLog("", "",
                            politics_commit_title.getText().toString());
                }
//                SkipUtil.skipToAddUserOperate(PoliticsCommitActivity.this, getOwnerName(), 11, 3, "问政成功", "" + singleResult.getInfoId(), Cache.getInstance().getCurrentChannelId());
//                addInvitation(Constances.ADD_INTEGRAL_SUBMISSION, true);
                finish();
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                if (TextUtils.isEmpty(errorMsg)) {
                    toast(R.string.rebllion_publish_failure);
                } else {
                    toast(errorMsg);
                }
//                showPublishFailure();
                closeProgress();
            }

            @Override
            public void onEnd() {
                closeProgress();
                Cache.getInstance().setUploadReb(false);
            }
        });
    }

    /**
     * 验证输入内容是否符合要求
     */
    private boolean inputCheck(){
        if(TextUtils.isEmpty(politics_commit_title.getText().toString().trim())||politics_commit_title.getText().toString().trim().length()<6){
            toast("请输入6-20个字标题");
            return false;
        }
        if(TextUtils.isEmpty(politics_content.getText().toString().trim())){
            toast("回音壁内容不能为空");
            return false;
        }
        if(TextUtils.isEmpty(politics_commit_name.getText().toString().trim())){
            toast("真是姓名不能为空");
            return false;
        }
        if(TextUtils.isEmpty(politics_commit_contact.getText().toString().trim())){
            toast("联系方式不能为空");
            return false;
        }
        return true;
    }
    /**
     * 上传图片、视频资源的回调，进一步上传整个报料内容
     */
    AbsNetCallBack mImgCallback = new AbsNetCallBack<String>(String.class) {
        @Override
        public void onSucStr(String result) {
            if (!TextUtils.isEmpty(result)) {
                PoliticsImgUpbean imgs = gson.fromJson(result, PoliticsImgUpbean.class);
                publish(imgs, null);
            }

        }

        @Override
        public void onError(Throwable ex, String errorMsg) {
            toast(errorMsg);
            closeProgress();
        }

        @Override
        public void onEnd() {
            closeProgress();
        }
    };
    /**
     * 上传图片、视频资源的回调，进一步上传整个报料内容
     */
    AbsNetCallBack mVideoCallback = new AbsNetCallBack<String>(String.class) {
        @Override
        public void onSucStr(String result) {
            if (!TextUtils.isEmpty(result)) {
                List<PoliticsUpVideo> video = gson.fromJson(result, ListTypeUtils.PoliticsUpVideo());
                publish(null, video);
            }

        }

        @Override
        public void onError(Throwable ex, String errorMsg) {
            toast(errorMsg);
            closeProgress();
        }

        @Override
        public void onEnd() {
            closeProgress();
        }
    };


    private ConfirmDialogFragment confirmFragment;
    public static final String REPORT_TAG = "report_fragment";

    private void showPublishFailure() {
        if (confirmFragment == null) {
            confirmFragment = new ConfirmDialogFragment();
        }
        confirmFragment.show(getSupportFragmentManager(), REPORT_TAG);
    }


    private void getLocation() {
        mLocationState = 0;
        refreshLocationState(null);
        if (SystemClock.elapsedRealtime() - mLocationTime >= 1000) {
            initLocation();
            mLocationTime = SystemClock.elapsedRealtime();
        } else {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    initLocation();
                    mLocationTime = SystemClock.elapsedRealtime();
                }
            }, 1000);
        }
    }

    private void locatingFailed(String errorStr) {
        if (locateFailTimes == 0) {
            toast(errorStr);
        }

        mLocationState = 2;
        refreshLocationState(null);

        locateFailTimes++;
        if (locateFailTimes < 3) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getLocation();
                }
            }, 1000);

        }

    }

    private void refreshLocationState(String location) {
        switch (mLocationState) {
            case 0:
                address_cv.setText(R.string.rebllion_publish_locating);
                break;
            case 1:
                address_cv.setText(location);
                break;
            case 2:
                address_cv.setText(R.string.rebllion_publish_locating_failed);
                break;
        }
    }

    private void checkLocationPermission() {
        mPermissionUtils = new PermissionUtils(this);
        mPermissionUtils.addPermission(Manifest.permission.READ_PHONE_STATE);
        mPermissionUtils.addPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
        mPermissionUtils.addPermission(Manifest.permission.ACCESS_FINE_LOCATION);
        mPermissionUtils.addPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
        mPermissionUtils.addPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);

        mPermissionUtils.setPermissionListener(new PermissionUtils.PermissionListener() {
            @Override
            public void onUserRefusesPermissions() {
                locatingFailed("用户拒绝了权限，定位无法进行, 如需重新授予权限，请进入手机的“设置-应用程序-SiChuanFocus2Android”中打开权限");
            }
        });

        if (mPermissionUtils.checkAndRequestPermissions()) {
            initLocation();
            getLocation();

        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            locatingFailed("用户拒绝了权限，定位无法进行, 如需重新授予权限，请进入手机的“设置-应用程序-SiChuanFocus2Android”中打开权限");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PermissionUtils.PERMISSIONS_REQUEST_CODE) {
            String msg = "本页面的定位功能需要用到以下权限：\n1. 读取手机状态\n2. 获取位置信息（基站）\n3. 获取位置信息（GPS）\n4. 读取手机存储的信息\n5. 写入信息到手机存储\n\n请授予这些权限确保定位功能可以正常运行。";
            if (mPermissionUtils.recheckPermissions(grantResults, msg)) {
                initLocation();
                getLocation();
            }
        }
    }

    /**
     * 开始定位
     */
    private void initLocation() {
        GaoDeLocationUtil.getInstance().registerOnLocatedListener(this);
        GaoDeLocationUtil.getInstance().startLocate(PoliticsCommitActivity.this);
    }

    @Override
    protected void onDestroy() {
        GaoDeLocationUtil.getInstance().stopLocate();
        Cache.getInstance().setUploadReb(false);
        super.onDestroy();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void afterTextChanged(Editable s) {
        int length = getStrLength(s.toString());
        if (length == 120) {
            toast(R.string.only_120_word);
        }
    }

    private int getStrLength(String str) {
        if (str == null) {
            return 0;
        }
        return str.length();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    }

    private boolean checkPhone() {
        if (TextUtils.isEmpty(politics_commit_contact.getText().toString()) || !politics_commit_contact.getText().toString().matches(Constances.MATCHER_PHONE)) {
            toast(R.string.please_input_valued_phone);
            return false;
        }
        return true;
    }

    private boolean checkTitle() {
        if (TextUtils.isEmpty(politics_commit_title.getText().toString())) {
            toast(R.string.please_input_title);
            return false;
        } else if (politics_commit_title.getText().toString().length() < 6 || politics_commit_title.getText().toString().length() > 20) {
            toast(R.string.number_warning);
            return false;
        }
        return true;
    }


    @Override
    public void onLocationChange(AMapLocation location) {
        GaoDeLocationUtil.getInstance().unregisterOnLocatedListener(this);
        GaoDeLocationUtil.getInstance().stopLocate();

        String locationStr;

        if (TextUtils.isEmpty(location.getCity()) || TextUtils.isEmpty(location.getDistrict())) {
            locatingFailed("获取定位失败，未知错误");
            return;
        }
        JLog.e("OnLocated", "-R--location =" + location.getCity());
        locationStr = location.getCity() + "-";    //获取城市信息
        locationStr += location.getDistrict();    //获取区县信息
        mLocationState = 1;
        refreshLocationState(locationStr);


    }


    private void showProtocol() {
        if (protocolFragment == null) {
            protocolFragment = new ProtocolFragment();
            Bundle bundle = new Bundle();
            bundle.putString("1", getResources().getString(R.string.protocol_41));
            bundle.putString("2", getResources().getString(R.string.protocol_42));
            bundle.putString("3", getResources().getString(R.string.protocol_43));
            bundle.putString("4", getResources().getString(R.string.protocol_44));
            bundle.putString("title", getResources().getString(R.string.text_rules_item_5));
            protocolFragment.setArguments(bundle);
        }
        if (!protocolFragment.isAdded()) {
            protocolFragment.show(getSupportFragmentManager(), PROTOCOL_TAG);
        }
    }

}
